import Dialog from 'tdesign-miniprogram/dialog/index';
import Message from 'tdesign-miniprogram/message/index';

import tools from '@/utils/tools';
import { getUserFeedbacks, submitFeedback, deleteFeedback } from '@/service/api/feedback';

const pagination = {
    page: 1,
    size: 10
};

const messageDefaultConfig = (content) => {
    return {
        context: this,
        offset: [60, 32],
        content: content
    };
};

Page({
    data: {
        title: '',
        description: '',
        feedbacks: [],
        popupShow: false,
        feedbackTitle: '',
        feedbackDetail: '',
        loadFinished: false
    },

    async loadMoreFeedbacks() {
        if (this.data.loadFinished) {
            return;
        }
        // 获取用户反馈
        const res = await getUserFeedbacks(pagination.page, pagination.size);
        if (res.problems.length <= 0) {
            this.setData({
                loadFinished: true
            });
            return;
        }
        // 把时间戳转为时间
        res.problems.forEach((item) => {
            item.submitTime = tools.timestampToDateTime(item.submitTime);
            if (item.responseTime) {
                item.responseTime = tools.timestampToDateTime(item.responseTime);
            }
        });
        this.setData({
            feedbacks: [...this.data.feedbacks, ...res.problems]
        });
        // 如果返回数据条数不满足页数说明加载完毕
        if (res.problems.length < pagination.size) {
            this.setData({
                loadFinished: true
            });
        }
        pagination.page++;
    },

    // 下拉刷新事件
    onPullDownRefresh: tools.throttle(async function () {
        // 重置数据
        this.setData({
            feedbacks: [],
            popupShow: false,
            loadFinished: false
        });
        pagination.page = 1;
        try {
            await this.loadMoreFeedbacks();
        } catch (err) {
            Message.error(messageDefaultConfig(err.message || '请求错误'));
        }
    }, 10000),

    async onReady() {
        try {
            pagination.page = 1;
            await this.loadMoreFeedbacks();
        } catch (err) {
            Message.error(messageDefaultConfig(err.message || '请求错误'));
        }
    },

    handleInputChange(e) {
        this.setData({
            title: e.detail.value
        });
    },

    handleResetContent() {
        this.setData({
            title: '',
            description: ''
        });
    },

    handleSubmitFeedback: tools.throttle(function () {
        if (this.data.description.length == 0 || this.data.title.length === 0) {
            Message.warning(messageDefaultConfig('请完成表单'));
            return;
        }
        if (this.data.description.length <= 10) {
            Message.warning(messageDefaultConfig('请最少输入十个字'));
            return;
        }
        Dialog.confirm({
            context: this,
            title: '提示',
            closeOnOverlayClick: true,
            content: '是否提交反馈',
            confirmBtn: '确定',
            cancelBtn: '取消'
        })
            .then(async () => {
                await submitFeedback(this.data.title, this.data.description);
                Message.success(messageDefaultConfig('反馈成功'));

                this.handleResetContent();
            })
            .catch((err) => {
                Message.warning(messageDefaultConfig(err));
            });
    }, 2000),

    onVisibleChange(e) {
        this.setData({
            popupShow: e.detail.visible
        });
    },

    checkDetail(e) {
        const { title, detail } = e.currentTarget.dataset;
        this.setData({
            popupShow: true,
            feedbackTitle: title,
            feedbackDetail: detail
        });
    },

    async handleDeleteFeedback(e) {
        const feedback = e.currentTarget.dataset.feedback;
        Dialog.confirm({
            context: this,
            title: '提示',
            closeOnOverlayClick: true,
            content: `是否${feedback.status === 0 ? '撤回' : '删除'}这条反馈`,
            confirmBtn: '确定',
            cancelBtn: '取消'
        })
            .then(async () => {
                await deleteFeedback(feedback.id);
                this.setData({
                    feedbacks: this.data.feedbacks.filter((item) => item.id !== feedback.id)
                });
                Message.success(messageDefaultConfig('请求成功'));
            })
            .catch((err) => {
                if (Object.keys(err).includes('trigger')) return;
                Message.warning(messageDefaultConfig(err));
            });
    },

    async handleScrollToLower() {
        await this.loadMoreFeedbacks();
    }
});
